/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ita.escolaita.ejb;

import br.ita.escolaita.model.entity.Disciplina;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import static br.ita.escolaita.util.EscolaItaUtil.isBlankOrNull;

/**
 *
 * @author Rafael
 */
@Stateless
public class DisciplinaEjbBean implements DisciplinaEjbLocal {

    @PersistenceContext(unitName = "escolaIta-ejbPU")
    private EntityManager em;

    public void salvar(Disciplina disciplina) {
        em.persist(disciplina);
        em.flush();
    }

    public void alterar(Disciplina disciplina) {
        em.merge(disciplina);
        em.flush();
    }

    public List<Disciplina> listarTodas() {
        Query findAllQuery = em.createNamedQuery("disciplina.findAll");
        List<Disciplina> disciplinas = findAllQuery.getResultList();
        return disciplinas;
    }

    public List<Disciplina> listar(Disciplina d) {
        StringBuilder sql = new StringBuilder();
        StringBuilder where = new StringBuilder();
        sql.append("SELECT d FROM Disciplina d ");
        if (!isBlankOrNull(d.getNome())) {
            where.append("WHERE UPPER(d.nome) LIKE UPPER('%").append(d.getNome()).append("%') ");
        }
        if (d.getProfessor() != null) {
            if (where.length() != 0){
                where.append("AND ");
            } else {
                where.append("WHERE ");
            }
            where.append("UPPER(d.professor.nome) LIKE UPPER('%").append(d.getProfessor().getNome()).append("%') ");
        }
        if(!isBlankOrNull(d.getPrograma())){
            if (where.length() != 0){
                where.append("AND ");
            } else {
                where.append("WHERE ");
            }
            where.append("UPPER(d.programa) LIKE UPPER('%").append(d.getPrograma()).append("%') ");
        }
        if (d.getSerie() != null && d.getSerie().getId() != null){
            if (where.length() != 0){
                where.append("AND ");
            } else {
                where.append("WHERE ");
            }
            where.append("d.serie.id = ").append(d.getSerie().getId()).append(" ");
        }
        Query findAllQuery = em.createQuery(sql.append(where).toString());
        List<Disciplina> disciplinas = findAllQuery.getResultList();        
        return disciplinas;
    }
}
